package com.haoran.grope.client;

import java.util.UUID;

import javax.annotation.PostConstruct;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ConfirmCallback;
import org.springframework.amqp.rabbit.core.RabbitTemplate.ReturnCallback;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//@Component
public class CalculatorClient implements ConfirmCallback,ReturnCallback{
	@Autowired
	private RabbitTemplate rabbitTemplate;
	
	@PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {  
            System.out.println("消息发送成功:" + correlationData);  
        } else {  
            System.out.println("消息发送失败:" + cause);  
        }  
        
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println(message.getMessageProperties().getCorrelationIdString() + " 发送失败");
        
    }
 
	
	public Object sum(int a,int b) {
		Object result = rabbitTemplate.convertSendAndReceive("amqp-sum",new int[] {a,b});
		return result;
	}
	
	//发送消息，不需要实现任何接口，供外部调用。
    public String send(String msg){
        System.out.println("开始发送消息 : " + msg.toLowerCase());
        Object convertSendAndReceive = rabbitTemplate.convertSendAndReceive("amqp-msg",(Object) msg, new CorrelationData(UUID.randomUUID().toString()));
        if(convertSendAndReceive != null) {
			String response = convertSendAndReceive.toString();
	        System.out.println("结束发送消息 : " + msg.toLowerCase());
	        System.out.println("消费者响应 : " + response + " 消息处理完成");
	        return response;
        }
        return null;
    }

	public Object hello(String string) {
		 
		return null;
	}

}
